package com.gitee.hljdrl.uikit;

import android.text.TextUtils;
import android.util.ArrayMap;

import com.gitee.hljdrl.uikit.basic.UIKitOptionEvent;


public final class UIKitOption implements UIKitOptionEvent {

    private static volatile UIKitOptionEvent INSTANCE = null;

    public static UIKitOptionEvent getInstance() {
        if (INSTANCE == null) { // 第一次检查（无锁）
            synchronized (UIKitOption.class) {
                if (INSTANCE == null) { // 第二次检查（加锁后）
                    INSTANCE = new UIKitOption();
                }
            }
        }
        return INSTANCE;
    }

    public static void unInstance(){
        INSTANCE = null;
    }

    // 防御反射攻击
    private UIKitOption() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Use getInstance()");
        }
    }

    ArrayMap<String, String> OPTION_MAP = new ArrayMap<>();
    // 防御反序列化（若需序列化）
    private Object readResolve() {
        return INSTANCE;
    }

    @Override
    public void setOption(String name, String value) {
        OPTION_MAP.put(name, value);
    }

    @Override
    public String getOption(String name, String defaultValue) {
        if (OPTION_MAP.containsKey(name)) {
            return OPTION_MAP.get(name);
        }
        return defaultValue;
    }

    @Override
    public long getOptionAsLong(String name, long defaultValue) {
        if (OPTION_MAP.containsKey(name)) {
            String value = OPTION_MAP.get(name);
            if (!TextUtils.isEmpty(value)) {
                try {
                    return Long.parseLong(value);
                } catch (Exception ex) {
                    return defaultValue;
                }
            }
        }
        return defaultValue;
    }
}
